package communicate;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Reader;

/**
 * IO 流中的 管道流 会阻塞
 * 可用于线程间的数据传输
 * 
 * 编写读取键盘输入然后打印出来
 * 
 * @author insight
 * @since 2021/8/30
 */
public class PipedIO {
    public static void main(String[] args) throws IOException {
        // 管道的接收端
        PipedReader in = new PipedReader();
        // 管道的输出端
        PipedWriter out = new PipedWriter();
        // 需要将两端连接起来形成管道
        out.connect(in);
        // 具有相同的效果
        // in.connect(out);
        
        new Thread(new Printer(in), "Printer").start();
        
        int ret = -1;
        while ((ret = System.in.read()) != -1) {
            out.write((char)ret);
        }
        
        out.close();
        in.close();
    }

    static class Printer implements Runnable {
        private Reader in;

        public Printer(Reader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int ret = -1;
            try {
                while ((ret = in.read()) != -1) {
                    System.out.print((char) ret);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}